import { ref, onMounted } from 'vue'

export const useFrontendTTS = () => {
  const isSpeaking = ref(false)
  const voicesLoaded = ref(false)

  // 确保语音数据已加载
  const loadVoices = () => {
    return new Promise<void>((resolve) => {
      if (voicesLoaded.value) {
        resolve()
        return
      }

      if (typeof speechSynthesis !== 'undefined' && speechSynthesis.onvoiceschanged !== undefined) {
        speechSynthesis.onvoiceschanged = () => {
          voicesLoaded.value = true
          resolve()
        }
      } else {
        // 对于不支持onvoiceschanged的浏览器，直接使用可用的语音
        setTimeout(() => {
          voicesLoaded.value = true
          resolve()
        }, 100)
      }
    })
  }

  // 使用浏览器Web Speech API朗读单词
  const speak = (word: string): Promise<void> => {
    return new Promise((resolve, reject) => {
      if (!word || word === '-') {
        console.warn('单词为空，无法朗读')
        resolve()
        return
      }

      // 检查浏览器是否支持Web Speech API
      if (!('speechSynthesis' in window)) {
        console.error('浏览器不支持Web Speech API')
        alert('您的浏览器不支持语音合成功能，请尝试使用最新版Chrome、Firefox或Edge浏览器。')
        reject(new Error('浏览器不支持Web Speech API'))
        return
      }

      try {
        // 获取并使用可用的英语语音
        const voices = speechSynthesis.getVoices()
        console.log('可用的语音列表:', voices)
        
        const utterance = new SpeechSynthesisUtterance(word)
        utterance.lang = 'en-US' // 设置为英语
        
        const englishVoice = voices.find(voice => 
          voice.lang.startsWith('en') || 
          voice.name.toLowerCase().includes('english') ||
          voice.name.toLowerCase().includes('en-')
        )
        
        if (englishVoice) {
          utterance.voice = englishVoice
          console.log('使用语音:', englishVoice.name)
        } else {
          console.warn('未找到英语语音，使用系统默认语音')
        }
        
        // 设置语音参数
        utterance.rate = 1.0
        utterance.pitch = 1.0
        utterance.volume = 1.0
        
        utterance.onstart = () => {
          console.log('开始朗读单词:', word)
          isSpeaking.value = true
        }
        
        utterance.onend = () => {
          console.log('朗读结束')
          isSpeaking.value = false
          resolve()
        }
        
        utterance.onerror = (event) => {
          console.error('Web Speech API朗读失败:', event)
          alert('朗读失败，请检查浏览器设置或尝试其他浏览器。')
          isSpeaking.value = false
          reject(new Error('Web Speech API朗读失败'))
        }

        // 取消之前的语音并播放新语音
        window.speechSynthesis.cancel()
        window.speechSynthesis.speak(utterance)
      } catch (error) {
        console.error('TTS功能出错:', error)
        alert('语音朗读功能出错，请检查浏览器设置。')
        isSpeaking.value = false
        reject(error)
      }
    })
  }

  // 停止朗读
  const stop = () => {
    if ('speechSynthesis' in window) {
      window.speechSynthesis.cancel()
      isSpeaking.value = false
    }
  }

  return {
    speak,
    stop,
    isSpeaking
  }
}